import menuStoreCreater from '@/store/menuStore'
import DuUtil from '@/utils/DuUtil'
import { indexRoute } from '@/router/modules/index.js' // 首页路由
import devPages from '@/router/modules/devPages.js' // 开发时的路由，（后台菜单还没有添加时）

// 路径->菜单
export const menuPathMap = new Map()

export function useAsyncRoute() {
  // 1. 准备main文件夹下所有组件 componentMap
  const getComponentMap = () => {
    const directives = import.meta.glob('../../views/main/**/*.vue')
    /*
    directives = {
                  "../views/main/dashboard/index.vue": () => import("/hzs/src/views/main/dashboard/index.vue"),
                  "../views/main/module1/menu1/test1/test1-1.vue": () => {…},
                  "../views/main/module1/menu1/test1/test1-2.vue": () => {…},
                  ...
                }
     */
    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>directives', directives)

    const componentMap = new Map() // view/main文件夹下的组件
    Object.keys(directives).forEach((key) => {
      // 格式化key
      const k = key.replace(/(..\/..\/views\/main|\.vue)/g, '')
      componentMap.set(k, directives[key])
    })
    return componentMap
  }

  // 2.设置菜单路由menuPathMap
  const setMenuPathMap = () => {
    const menuStore = menuStoreCreater()
    const getMenuPath = (menus) => {
      menus.forEach((menu) => {
        // 注：menuPathMap里没有白名单和外链
        if (menu.isOutLink || menu.isWhiteList) {
          return
        }
        if (menu.children && menu.children.length > 0) {
          getMenuPath(menu.children)
        } else {
          const path = menu.path.split('?')[0]
          menuPathMap.set(path, menu)
        }
      })
    }
    menuStore.modules.forEach((module) => {
      getMenuPath(module.menu)
    })
  }

  const getAsyncRoutes = () => {
    // 1.
    const componentMap = getComponentMap()
    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>componentMap', componentMap)

    // 2.
    setMenuPathMap()
    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>menuPathMap', menuPathMap)

    // 修改菜单组件name （改成在路由守卫处理）
    // reNameComp()  // 设计成组件的name与路由的name保持一致 (因为keep-alive的:include匹配的是组件的name属性及comp.default.name)

    // 3.生成最终路由
    const menuRoutes = [] // 路由数据
    menuPathMap.forEach((value, key) => {
      const comp = componentMap.get(key)
      if (!DuUtil.isUndefined(comp)) {
        menuRoutes.push({
          path: key,
          component: comp,
          name: key,
          meta: value.meta,
        })
      }
    })
    console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>menuRoutes', menuRoutes)

    // 4.塞入indexRoute的children里，再return
    if (import.meta.env.MODE === 'development') {
      indexRoute.children = [...indexRoute.children, ...menuRoutes, ...devPages] //测试环境把开发阶段的路由加上
    } else {
      indexRoute.children = [...indexRoute.children, ...menuRoutes]
    }

    return indexRoute
  }

  return {
    getAsyncRoutes,
  }
}
